<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
		<el-form-item label="学校" prop="bjXxid">
		  <el-select v-model="queryParams.bjXxid" @change="handleQuery" placeholder="请选择学校" :disabled="isXxidFlag" clearable>
		    <el-option
		      v-for="d in dept_self"
		      :key="d.value"
		      :label="d.label"
		      :value="d.value"
		    />
		  </el-select>
		</el-form-item>
      <el-form-item label="班级名称" prop="bjName">
        <el-input
          v-model="queryParams.bjName"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="bjNj">
        <el-select v-model="queryParams.bjNj" @change="handleQuery" placeholder="请选择年级" clearable>
          <el-option
            v-for="dict in tc_nj"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
	  
<!-- 	  
      <el-form-item label="启用状态" prop="bjStatus">
        <el-select v-model="queryParams.bjStatus" placeholder="请选择启用状态" clearable>
          <el-option
            v-for="dict in tc_qyzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
	  <el-form-item label="学校ID" prop="bjXxid">
	    <el-input
	      v-model="queryParams.bjXxid"
	      placeholder="请输入学校ID"
	      clearable
	      @keyup.enter="handleQuery"
	    />
	  </el-form-item>
	  -->
	  
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tc:class:add']"
        >新增</el-button>
      </el-col>
	  
<!-- 	  
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tc:class:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tc:class:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tc:class:export']"
        >导出</el-button>
      </el-col>
		 -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
	  <el-table-column type="index" label="序号" width="55" />
      <el-table-column label="班级名称" align="center" prop="bjName" />
      <el-table-column label="年级" align="center" prop="bjNj">
        <template #default="scope">
          <dict-tag :options="tc_nj" :value="scope.row.bjNj"/>
        </template>
      </el-table-column>
       <el-table-column label="学校" align="center" >
        <template #default="scope">
          {{ dept_self.find(f=>f.value==scope.row.bjXxid).label }}
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="bjStatus">
        <template #default="scope">
          <dict-tag :options="tc_qyzt" :value="scope.row.bjStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="bjCreate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.bjCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="bjUpdate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.bjUpdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tc:class:edit']">修改</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tc:class:remove']">删除</el-button> -->
        </template>
      </el-table-column>
	  
	  
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级对话框 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-form ref="classRef" :model="form" :rules="rules" label-width="80px">
		  <el-form-item label="学校" prop="bjXxid">
		    <el-select style="width: 100%;" v-model="form.bjXxid" placeholder="学校" :disabled="isXxidFlag" clearable>
		      <el-option
		        v-for="d in dept_self"
		        :key="d.value"
		        :label="d.label"
		        :value="d.value"
		      />
		    </el-select>
		  </el-form-item>
       
        <el-form-item label="年级" prop="bjNj">
          <el-select  style="width: 100%;" v-model="form.bjNj" placeholder="请选择年级">
            <el-option
              v-for="dict in tc_nj"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="班级名称" prop="bjName">
          <el-input v-model="form.bjName" placeholder="请输入班级名称" />
        </el-form-item>
<!--        <el-form-item label="启用状态" prop="bjStatus">
          <el-select v-model="form.bjStatus" placeholder="请选择启用状态">
            <el-option
              v-for="dict in tc_qyzt"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
		
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Class">
import { listClass, getClass, delClass, addClass, updateClass } from "@/api/tc/class";
import { getDept,listDept } from "@/api/system/dept";
import useUserStore from '@/store/modules/user'
import { checkPermi, checkRole } from "@/utils/permission"; // 1. 导入权限判断函数
var userStore=useUserStore();

const { proxy } = getCurrentInstance();
const { tc_nj, tc_qyzt } = proxy.useDict('tc_nj', 'tc_qyzt');

const classList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dept_self = ref([]);
const isXxidFlag=ref(false);
const data = reactive({
  form: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bjName: null,
    bjNj: null,
    bjStatus: '1',
    bjXxid: null,
  },
  rules: {
    bjXxid: [
      { required: true, message: "学校不能为空", trigger: "blur" }
    ],
    bjName: [
      { required: true, message: "班级不能为空", trigger: "blur" }
    ],
    bjNj: [
      { required: true, message: "年级不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

 onMounted(() => {
	// console.log(userStore.user)
      // console.log('组件已经挂载')
      // console.log(tc_qyzt.value[0].value)
    // this.selected = this.options[0].value; // 在组件挂载后设置默认选中第一个选项
	// this.form.tc_qyzt=tc_qyzt.value[0].value;
	// console.log(queryParams.value.bjStatus)
	// queryParams.value.bjStatus = tc_qyzt.value[0].value;
	getDeptInfo();
 })
/** 查询班级列表 */
function getList() {
  loading.value = true;
  // console.log(queryParams.value)
  // console.log(userStore.user)
  // queryParams.value.bjXxid=userStore.user.deptId
  
  listClass(queryParams.value).then(response => {
    classList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getDeptInfo(){
		// console.log(userStore.user)
		if(checkRole(['admin','common'])){
			listDept({}).then(response => {
			  	response.data.forEach(function (element) {
			  	  // 遍历数组，对每个元素进行操作
				   if(element.xxlevel !=null && element.xxlevel != ''){
						dept_self.value.push({"value":element.deptId,"label":element.deptName});
				   }
			  	});
				queryParams.value.bjXxid=dept_self.value[0].value;
				form.bjXxid=dept_self.value[0].value;
				getList();
			});
			isXxidFlag.value=false;
		}else{
			dept_self.value.push({"value":userStore.user.deptId,"label":userStore.user.dept.deptName});
			queryParams.value.bjXxid=dept_self.value[0].value;
			form.bjXxid=dept_self.value[0].value;
			isXxidFlag.value=true;
			getList();
		}
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    bjName: null,
    bjNj: null,
    bjDel: null,
    bjStatus: tc_qyzt.value[0].value,
    bjCreate: null,
    bjCreateby: null,
    bjXxid: dept_self.value[0].value,
    bjUpdate: null,
    bjUpdateby: null
  };
  proxy.resetForm("classRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.bjStatus = '1';
  queryParams.value.bjXxid=dept_self.value[0].value;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.bjStatus="1";
  open.value = true;
  title.value = "添加班级";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getClass(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改班级";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["classRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateClass(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
		  // console.log(userStore.user)
		  // form.value.bjXxid=userStore.user.dept.deptId;
		  form.value.bjCreateby=userStore.user.userName;
		  form.value.bjUpdateby=userStore.user.userName;
		  // console.log(form.value)
		  // return;
        addClass(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除班级编号为"' + _ids + '"的数据项？').then(function() {
    return delClass(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tc/class/export', {
    ...queryParams.value
  }, `class_${new Date().getTime()}.xlsx`)
}

</script>
